package com.mzj.saas.rent;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.repository.core.AjaxResult;
import com.haixiaoke.saas.repository.core.BaseController;
import com.haixiaoke.saas.repository.service.IUserService;
import com.mzj.saas.annotation.CheckAuth;
import com.mzj.saas.util.LoginUserUtil;
import com.mzj.saas.util.UniAppUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * @Author Dell
 * @Date 2023/6/10
 **/
@RestController
@RequestMapping("/appUser")
public class AppUserController extends BaseController {

    @Autowired
    private LoginUserUtil loginUserUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserService iUserService;

    @CheckAuth
    @PutMapping("update/{mobileDevicesId}")
    public AjaxResult updateMobileDevicesId(@PathVariable("mobileDevicesId") String mobileDevicesId) {
        String userId = loginUserUtil.getId();

        if (StrUtil.isEmpty(mobileDevicesId)) {
            logger.error("更新的设备id为空，用户id为：{}",userId);
            return toAjax(0);
        }

        //修改saas_user表
        int result = iUserService.updateMobileDevicesId(mobileDevicesId, userId);
        if (result == 0) {
            return error("设备id更新失败");
        }
        Object o = redisTemplate.opsForValue().get(UniAppUtil.UNI_APP_ORDER_KEY + userId);
        if (StrUtil.isNotEmpty(userId) && ObjectUtil.isNotEmpty(o)) {
            List<String> mobileDevicesList = Arrays.asList(mobileDevicesId);
            String[] split = String.valueOf(o).split(",");
            for (String string : split) {
                UniAppUtil.sendMessage("房管家通知", "您有新的订单", string, mobileDevicesList);
            }
            redisTemplate.delete(UniAppUtil.UNI_APP_ORDER_KEY + userId);
        }
        return toAjax(userId == null ? 0 : 1);
    }
}
